<template>
  <div>
    <!-- 查询栏 -->
    <div class="toolbar">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-date-picker v-model="startDate" type="date" placeholder="开始日期" style="width: 100%" />
        </el-col>
        <el-col :span="6">
          <el-date-picker v-model="endDate" type="date" placeholder="结束日期" style="width: 100%" />
        </el-col>
        <el-col :span="6">
          <el-input placeholder="请输入车位名称" v-model="searchName" />
        </el-col>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-row>
    </div>

    <!-- 操作栏 -->
    <div class="button-bar">
      <el-button type="danger" icon="el-icon-delete" @click="handleBatchDelete">批量删除</el-button>
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="paginatedData" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="车位ID" width="80" />
      <el-table-column prop="community" label="所属小区" width="140" />
      <el-table-column prop="code" label="车位编号" width="140" />
      <el-table-column prop="name" label="车位名称" width="160" />
      <el-table-column label="当前状态" width="120">
        <template v-slot="scope">
          <el-button
            :type="scope.row.status === '闲置' ? 'success' : 'danger'"
            size="mini"
            @click="prepareToggle(scope.row)">
            {{ scope.row.status }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="160" />
      <el-table-column label="操作" width="100">
        <template v-slot="scope">
          <i class="el-icon-edit" @click="editRow(scope.row)" />
          <i class="el-icon-delete" @click="confirmDelete(scope.row)" />
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      layout="total, prev, pager, next, jumper"
      :current-page="currentPage"
      :page-size="pageSize"
      :total="filteredData.length"
      @current-change="handlePageChange"
      style="margin-top: 20px; text-align: center;" />

    <!-- 状态确认 -->
    <el-dialog
      :title="statusTarget?.status === '闲置' ? '启用车位' : '释放车位'"
      :visible.sync="statusDialogVisible"
      width="30%">
      <p>确定将该车位状态改为【{{ statusTarget?.status === '闲置' ? '使用中' : '闲置' }}】？</p>
      <span slot="footer" class="dialog-footer">
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmToggleStatus">确定</el-button>
      </span>
    </el-dialog>

    <!-- 添加 / 编辑弹窗 -->
    <el-dialog :title="editForm.id ? '编辑车位' : '添加车位'" :visible.sync="editDialogVisible" width="500px">
      <el-form :model="editForm" label-width="100px">
        <el-form-item label="车位ID">
          <el-input v-model="editForm.id" disabled />
        </el-form-item>
        <el-form-item label="车位名称">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="车位编号">
          <el-input v-model="editForm.code" />
        </el-form-item>
        <el-form-item label="当前状态">
          <el-select v-model="editForm.status">
            <el-option label="闲置" value="闲置" />
            <el-option label="使用中" value="使用中" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="editForm.createTime" disabled />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      startDate: '',
      endDate: '',
      searchName: '',
      currentPage: 1,
      pageSize: 5,
      selection: [],
      statusDialogVisible: false,
      statusTarget: null,
      editDialogVisible: false,
      editForm: {
        id: null,
        name: '',
        code: '',
        status: '闲置',
        createTime: ''
      },
      tableData: [
        { id: 1, community: '金华万府', code: 'P001', name: '地下A1', status: '闲置', createTime: '2024-06-01 10:00:00' },
        { id: 2, community: '星河时代', code: 'P002', name: '地上B2', status: '使用中', createTime: '2024-06-05 11:30:00' },
        { id: 3, community: '绿洲花园', code: 'P003', name: '地下C3', status: '闲置', createTime: '2024-06-08 09:15:00' },
      ],
    };
  },
  computed: {
    filteredData() {
      return this.tableData.filter(item => {
        const matchesName = !this.searchName || item.name.includes(this.searchName);
        const itemDate = new Date(item.createTime);
        const inDateRange =
          (!this.startDate || itemDate >= new Date(this.startDate)) &&
          (!this.endDate || itemDate <= new Date(this.endDate));
        return matchesName && inDateRange;
      });
    },
    paginatedData() {
      const start = (this.currentPage - 1) * this.pageSize;
      return this.filteredData.slice(start, start + this.pageSize);
    }
  },
  methods: {
    handleSearch() {
      this.currentPage = 1;
    },
    resetSearch() {
      this.searchName = '';
      this.startDate = '';
      this.endDate = '';
      this.currentPage = 1;
    },
    handleSelectionChange(val) {
      this.selection = val;
    },
    handlePageChange(page) {
      this.currentPage = page;
    },
    handleAdd() {
      const maxId = Math.max(...this.tableData.map(item => item.id), 0);
      const now = new Date().toISOString().slice(0, 19).replace('T', ' ');
      this.editForm = {
        id: maxId + 1,
        name: '',
        code: '',
        status: '闲置',
        createTime: now
      };
      this.editDialogVisible = true;
    },
    editRow(row) {
      this.editForm = { ...row };
      this.editDialogVisible = true;
    },
    saveEdit() {
      const index = this.tableData.findIndex(item => item.id === this.editForm.id);
      if (index !== -1) {
        this.$set(this.tableData, index, { ...this.editForm });
      } else {
        this.tableData.push({ ...this.editForm, community: '默认小区' });
      }
      this.$message.success('保存成功');
      this.editDialogVisible = false;
    },
    confirmDelete(row) {
      this.$confirm(`确定要删除车位 ${row.name} 吗？`, '删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.tableData = this.tableData.filter(item => item.id !== row.id);
        this.$message.success('删除成功');
      });
    },
    handleBatchDelete() {
      if (!this.selection.length) {
        this.$message.warning('请选择要删除的记录');
        return;
      }
      this.$confirm('确定要批量删除选中的车位吗？', '批量删除确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const ids = this.selection.map(item => item.id);
        this.tableData = this.tableData.filter(item => !ids.includes(item.id));
        this.$message.success('批量删除成功');
      });
    },
    prepareToggle(row) {
      this.statusTarget = row;
      this.statusDialogVisible = true;
    },
    confirmToggleStatus() {
      if (this.statusTarget) {
        this.statusTarget.status = this.statusTarget.status === '闲置' ? '使用中' : '闲置';
        this.$message.success('状态更新成功');
      }
      this.statusDialogVisible = false;
      this.statusTarget = null;
    }
  }
};
</script>

<style scoped>
.toolbar {
  margin-bottom: 20px;
}
.button-bar {
  background: #f2f2f2;
  padding: 6px 10px;
  margin-bottom: 20px;
}
.el-button {
  margin-right: 10px;
}
.el-icon-edit, .el-icon-delete {
  cursor: pointer;
  margin-right: 10px;
  color: #2a6496;
}
.dialog-footer {
  text-align: right;
}
</style>
